/**
 * jquery-GeoKBD 0.1 - jQuery Georgian virtual keyboard and text convertation library
 *
 * Copyright (c) 2011 Alexander Glonti (http://www.about.ge)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * 
 * Original idea by Ioseb Dzmanashvili
 * http://www.code.ge/geokbd
 */
 
jQuery.fn.GeoKBD = function(settings){
	var enabled = true;
	if(enabled==false) return false;
	//initial GeoKBD options
	var options = jQuery.extend({
		init_lang: 'ka',
		switcher: jQuery('#geo'),
		switcherSymbol: '`'
	}, settings);

	options.switcherKey = options.switcherSymbol.charCodeAt();

	if(options.switcher.length>0){
		  options.init_lang = jQuery(options.switcher).is(':checked') ? 'ka' : 'en';
		jQuery(options.switcher).change(function(){
				options.init_lang = jQuery(this).is(':checked') ? 'ka' : 'en';
		});
	}

//////////////////////////////////

	function pasteTo(field,text) {

		if(jQuery(field).attr('maxlength')){
			var tl = jQuery(field).val().length;
			var fl = jQuery(field).attr('maxlength');
			var diff = fl - (tl+text.length);
			if(diff<0){
				text = text.substring(0,diff);
			}
		}
		field.focus();
		if (document.selection) {
			var selection = document.selection;
			var range = selection.createRange();
			range.colapse;
			if (range) {
				range.text = text;
			}
		} else if (field.selectionStart || field.selectionEnd) {
			var scrollTop = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
			var value = field.value.substring(0, start) + text + field.value.substring(end, field.value.length);
			field.value = value;
			field.scrollTop = scrollTop;
			field.selectionStart = field.selectionEnd = start + text.length;
		} else {
			field.value += text;
			field.selectionStart = field.selectionEnd = field.value.length;
		}
	}
//////////////////////////////////
	function translateToKA(t){
		/**
		 * Original idea by Irakli Nadareishvili
		 * http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
		 */
		var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
		for (var i = 0; i < t.length; i++) {
			chr = t.substr(i, 1);
			if ((index = symbols.indexOf(chr)) >= 0) {
				text.push(String.fromCharCode(index + 4304));
			} else {
				text.push(chr);
			}
		}
		return text.join('');
	}
//////////////////////////////////
	jQuery(this).keypress(function(e) {
		if(enabled==true){
			if(e.charCode==options.switcherKey) {
				if((options.init_lang=='ka')){
					options.init_lang = 'en';
					jQuery(options.switcher).attr('checked',false);
				} else {
					options.init_lang = 'ka';
					jQuery(options.switcher).attr('checked',true);
				}
				return false;
			}
			if(options.init_lang=='ka'){
				var s = e.which;
				s = String.fromCharCode(s);
				s = translateToKA(s);
				pasteTo(this,s);
				return false;
			} else {
				return true;
			}
		}
	});
}

